import React, { useState, useEffect, useCallback } from 'react';
import { useParams, useNavigate } from 'react-router-dom';
import {
    Card,
    Form,
    Input,
    Select,
    DatePicker,
    Button,
    Space,
    message,
    Tag,
    Divider
} from 'antd';
import {
    SaveOutlined,
    ArrowLeftOutlined
} from '@ant-design/icons';
import { taskService } from '../../services/taskService';
import { stepService } from '../../services/stepService';
import dayjs from 'dayjs';
import { PRIORITY_OPTIONS } from '../../constants/priorityConstants';
import StepList from "../Steps/StepList";
import { v4 as uuidv4 } from 'uuid'; // 需要安装: npm install uuid

const { TextArea } = Input;
const { Option } = Select;

// 状态映射常量，确保与列表页面一致
const STATUS_MAPPING = {
    1: 'NOT_STARTED', // 待开始
    2: 'IN_PROGRESS', // 进行中
    3: 'COMPLETED',   // 已完成
    4: 'CANCELLED'    // 已取消
};

// 反向状态映射，用于表单提交时转换
const REVERSE_STATUS_MAPPING = {
    'NOT_STARTED': 1,
    'IN_PROGRESS': 2,
    'COMPLETED': 3,
    'CANCELLED': 4
};

// 临时步骤存储服务
const tempStepService = {
    steps: [],

    // 获取所有步骤
    getSteps: function() {
        return Promise.resolve({
            data: {
                data: this.steps
            }
        });
    },

    // 创建步骤
    createStep: function(taskId, stepData) {
        const newStep = {
            ...stepData,
            id: `temp-${uuidv4()}`,
            taskId: taskId || 'temp',
            createdAt: new Date().toISOString(),
            updatedAt: new Date().toISOString()
        };

        this.steps.push(newStep);
        return Promise.resolve({ data: { data: newStep } });
    },

    // 更新步骤
    updateStep: function(stepId, stepData) {
        const index = this.steps.findIndex(step => step.id === stepId);

        if (index !== -1) {
            const updatedStep = {
                ...this.steps[index],
                ...stepData,
                updatedAt: new Date().toISOString()
            };

            this.steps[index] = updatedStep;
            return Promise.resolve({ data: { data: updatedStep } });
        }

        return Promise.reject(new Error('步骤不存在'));
    },

    // 更新步骤状态
    updateStepStatus: function(stepId, isCompleted) {
        return this.updateStep(stepId, { isCompleted });
    },

    // 删除步骤
    deleteStep: function(stepId) {
        const initialLength = this.steps.length;
        this.steps = this.steps.filter(step => step.id !== stepId);

        if (this.steps.length < initialLength) {
            return Promise.resolve({ data: { success: true } });
        }

        return Promise.reject(new Error('步骤不存在'));
    },

    // 获取所有临时步骤
    getAllSteps: function() {
        return this.steps;
    },

    // 清空所有临时步骤
    clearSteps: function() {
        this.steps = [];
    }
};

const TaskForm = () => {
    const { id } = useParams();
    const navigate = useNavigate();
    const [form] = Form.useForm();
    const [loading, setLoading] = useState(false);
    const [task, setTask] = useState(null);
    const [submitting, setSubmitting] = useState(false);

    const isEdit = !!id;

    // 获取任务详情
    const fetchTask = useCallback(async () => {
        if (!isEdit) return;

        setLoading(true);
        try {
            const response = await taskService.getTask(id);
            const taskData = response.data.data;
            setTask(taskData);

            // 转换数据格式以适应表单
            const formData = {
                ...taskData,
                // 如果后端返回的状态是数字，则转换为字符串
                status: typeof taskData.status === 'number'
                    ? STATUS_MAPPING[taskData.status]
                    : taskData.status,
                dueDate: taskData.dueDate ? dayjs(taskData.dueDate) : null,
                startDate: taskData.startDate ? dayjs(taskData.startDate) : null,
            };

            form.setFieldsValue(formData);
        } catch (error) {
            message.error('获取任务信息失败');
        } finally {
            setLoading(false);
        }
    }, [id, isEdit, form]);

    useEffect(() => {
        fetchTask();

        // 清空临时步骤，以防有残留
        if (!isEdit) {
            tempStepService.clearSteps();
        }

        return () => {
            // 组件卸载时清空临时步骤
            if (!isEdit) {
                tempStepService.clearSteps();
            }
        };
    }, [fetchTask, isEdit]);

    // 表单提交处理
    const handleSubmit = async (values) => {
        setSubmitting(true);
        try {
            // 转换数据格式以适应 API
            const taskData = {
                ...values,
                // 如果表单中的状态是字符串，则转换为数字
                status: REVERSE_STATUS_MAPPING[values.status] || values.status,
                dueDate: values.dueDate ? values.dueDate.format('YYYY-MM-DD') : null,
                startDate: values.startDate ? values.startDate.format('YYYY-MM-DD') : null
            };

            let taskId;
            if (isEdit) {
                await taskService.updateTask(id, taskData);
                message.success('任务更新成功');
                taskId = id;
            } else {
                // 创建新任务
                const response = await taskService.createTask(taskData);
                taskId = response.data.data.id; // 假设API返回新创建的任务ID

                // 如果有临时步骤，将它们关联到新任务
                const tempSteps = tempStepService.getAllSteps();
                if (tempSteps.length > 0) {
                    const stepPromises = tempSteps.map(step => {
                        // 准备步骤数据，移除临时ID相关信息
                        const stepData = {
                            title: step.title,
                            description: step.description,
                            estimatedHours: step.estimatedHours,
                            expectedEndDate: step.expectedEndDate,
                            orderNum: step.orderNum,
                            isCompleted: step.isCompleted || false
                        };

                        // 创建步骤并关联到新任务
                        return stepService.createStep(taskId, stepData);
                    });

                    await Promise.all(stepPromises);

                    // 清空临时步骤
                    tempStepService.clearSteps();
                }

                message.success('任务创建成功');
            }

            navigate('/tasks');
        } catch (error) {
            message.error(isEdit ? '更新任务失败' : '创建任务失败');
            console.error('Error submitting task:', error);
        } finally {
            setSubmitting(false);
        }
    };

    return (
        <Card
            title={<Space size={0}><Button icon={<ArrowLeftOutlined />} onClick={() => navigate('/tasks')}>返回</Button><span>{isEdit ? '编辑任务' : '新建任务'}</span></Space>}
            loading={loading && !submitting}
            styles={{ body: { padding: '16px' } }}
        >
            <Form
                form={form}
                layout="vertical"
                onFinish={handleSubmit}
                style={{ maxWidth: 800 }}
                initialValues={{ priority: 0, status: 'NOT_STARTED' }}
                size="middle"
            >
                <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '12px' }}>
                    <Form.Item name="title" label="任务标题" rules={[{ required: true, message: '请输入任务标题' }]}>
                        <Input placeholder="请输入任务标题" />
                    </Form.Item>

                    <Form.Item name="priority" label="优先级" rules={[{ required: true, message: '请选择优先级' }]}>
                        <Select placeholder="请选择优先级">
                            {PRIORITY_OPTIONS.map(option => (
                                <Option key={option.value} value={option.value}>
                                    <Tag color={option.color}>{option.label}</Tag>
                                </Option>
                            ))}
                        </Select>
                    </Form.Item>
                </div>

                <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '12px' }}>
                    <Form.Item name="status" label="状态" rules={[{ required: true, message: '请选择状态' }]}>
                        <Select placeholder="请选择状态">
                            <Option value="NOT_STARTED">待开始</Option>
                            <Option value="IN_PROGRESS">进行中</Option>
                            <Option value="COMPLETED">已完成</Option>
                            <Option value="CANCELLED">已取消</Option>
                        </Select>
                    </Form.Item>

                    <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '12px' }}>
                        <Form.Item name="startDate" label="开始日期" style={{ marginBottom: '12px' }}>
                            <DatePicker style={{ width: '100%' }} placeholder="开始日期" />
                        </Form.Item>

                        <Form.Item name="dueDate" label="截止日期" style={{ marginBottom: '12px' }}>
                            <DatePicker style={{ width: '100%' }} placeholder="截止日期" />
                        </Form.Item>
                    </div>
                </div>

                <Form.Item name="description" label="任务描述" style={{ marginBottom: '12px' }}>
                    <TextArea rows={3} placeholder="请输入任务描述" />
                </Form.Item>

                <Form.Item style={{ marginBottom: '0', marginTop: '12px' }}>
                    <Space>
                        <Button type="primary" htmlType="submit" loading={submitting} icon={<SaveOutlined />} size="middle">
                            {isEdit ? '更新任务' : '创建任务'}
                        </Button>
                        <Button onClick={() => navigate('/tasks')} size="middle">取消</Button>
                    </Space>
                </Form.Item>
            </Form>
            <Divider />

            {/* 使用 StepList 组件，但传递不同的服务和任务ID */}
            <StepList
                taskId={isEdit ? id : 'temp'}
                isCreating={!isEdit}
                stepService={isEdit ? stepService : tempStepService}
            />
        </Card>
    );
};

export default TaskForm;
